package com.agmte.api.common.crud.core;

import com.agmte.api.common.crud.annotation.NULL;
import com.agmte.api.common.crud.tableAutoCreate.FieldInfo;
import com.agmte.api.common.crud.tableAutoCreate.TableHelper;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class TypeConversion {

    /**
     * 转化存入数据库
     *
     * @param entity
     * @param fieldName
     * @param value
     * @return
     */
    public static Object convertToDatabase(Class<?> entity, String fieldName, Object value) {
        FieldInfo f = TableHelper.getField(entity, fieldName);
        if (f != null && f.getTypeHandler() != null
                && !NULL.class.equals(f.getTypeHandler())) {
            try {
                if (f.getFieldType().equals(List.class)) {
                    value = JSON.toJSONString(value);
                } else {
                    value = JSON.toJSONString(value);
                }
            } catch (Exception e) {
                log.error(fieldName + " 解析错误", e);
                return null;
            }
        }
        return value;
    }

    /**
     * 转换为实体所用
     *
     * @param entity
     * @param fieldName
     * @param value
     * @return
     */
    public static Object convertToEntity(Class<?> entity, String fieldName, Object value) {
        FieldInfo f = TableHelper.getField(entity, fieldName);
        if (f != null && f.getTypeHandler() != null
                && !NULL.class.equals(f.getTypeHandler())) {
            try {
                if (f.getFieldType().equals(List.class)) {
                    value = JSON.parseArray(value.toString(), f.getTypeHandler());
                } else {
                    value = JSON.parseObject(value.toString(), f.getTypeHandler());
                }
            } catch (Exception e) {
                log.error(fieldName + " 解析错误", e);
                return null;
            }
        }
        return value;
    }
}
